package flex.cc.uac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import eu.bitwalker.useragentutils.UserAgent;
import flex.cc.PublicUtil;
import flex.cc.base.constant.GlobalConstant;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.base.enums.ErrorCodeEnum;
import flex.cc.core.enums.LogTypeEnum;
import flex.cc.core.utils.RequestUtil;
import flex.cc.system.service.DictCodeService;
import flex.cc.system.vo.DictOptionVo;
import flex.cc.uac.dao.UacUserAreaDao;
import flex.cc.uac.dao.UacUserDao;
import flex.cc.uac.dto.BindRoleDto;
import flex.cc.uac.dto.BindUserRolesDto;
import flex.cc.uac.dto.menu.UserMenuDto;
import flex.cc.uac.entity.*;
import flex.cc.uac.enums.UacUserSourceEnum;
import flex.cc.uac.exceptions.UacBizException;
import flex.cc.uac.service.*;
import flex.cc.uac.vo.CompanyTreeVo;
import flex.cc.uac.vo.UserBindRoleVo;
import flex.cc.uac.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@Service("uacUserService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class UacUserServiceImpl extends ServiceImpl<UacUserDao, UacUserEntity> implements UacUserService {

//    @Resource
//    private UacActionService uacActionService;
    @Resource
    private UacCompanyUserService uacCompanyUserService;
    @Resource
    private UacCompanyService uacCompanyService;
    //private UacGroupUserService uacGroupUserService;
    @Resource
    private UacLogService uacLogService;
    @Resource
    private UacUserTokenService uacUserTokenService;
    @Resource
    private UacUserDao uacUserDao;
    @Resource
    private UacUserAreaDao uacUserAreaDao;

    @Resource
    private UacRoleService uacRoleService;
    @Resource
    private UacRoleUserService uacRoleUserService;

    @Resource
    private UacUserAreaService uacUserAreaService;

    @Resource
    private DictCodeService dictCodeService;

//    @Resource
//    private PasswordEncoder passwordEncoder;

    @Resource
    private TaskExecutor taskExecutor;

    @Override
    public IPage<UacUserEntity> queryUserListWithPage(UacUserEntity uacUser){
    	// uacUser.setBelongComCode(RequestUtil.getLoginUser().getComCode());
    	Page<UacUserEntity> page = new Page<>(uacUser.getPageNum(),uacUser.getPageSize());
    	IPage<UacUserEntity> pageData=this.uacUserDao.queryUserListWithPage(page, uacUser);
    	return pageData;
    }


    @Override
    public void saveUacUser(UacUserEntity uacUser, LoginAuthDto loginAuthDto) {
        String mobileNo = uacUser.getMobileNo();
        String loginName = uacUser.getLoginName();
        Preconditions.checkArgument(!StringUtils.isEmpty(loginName), "用户名不能为空");
        UacUserEntity user = this.getOne(new QueryWrapper<UacUserEntity>().eq("mobile_no",mobileNo));
        if (PublicUtil.isNotEmpty(user) && !user.getId().equals(uacUser.getId())) {
            Preconditions.checkArgument(PublicUtil.isEmpty(user), ErrorCodeEnum.UAC10011013.msg());
        }
        Preconditions.checkArgument(uacUser.getGroupId() != null, "组织不能为空");
        uacUser.setUpdateInfo(loginAuthDto);
        if (uacUser.isNew()) {
            String loginPwd = uacUser.getLoginPwd();
            if(StringUtils.isEmpty(loginPwd)) {
                uacUser.setLoginPwd("zx123456789");
            }
            // 验证用户名是否存在
            int count = this.count(new QueryWrapper<UacUserEntity>().eq("login_name",loginName));
            if (count > 0) {
                throw new UacBizException(ErrorCodeEnum.UAC10011025, loginName);
            }
            // 1.保存用户信息
            uacUser.setLoginName(loginName);
            uacUser.setUserSource(UacUserSourceEnum.INSERT.getKey());
            this.save(uacUser);
            // 新增用户负责区域信息
            this.saveUserAreaInfo(uacUser,loginAuthDto);
            // TODO 【去掉】2.添加业务机构关联
            /*UacCompanyUserEntity uacCompanyUser = new UacCompanyUserEntity();
            uacCompanyUser.setComCode(uacUser.getBelongComCode());
            uacCompanyUser.setUserCode(uacUser.getUserCode());
            uacCompanyUser.setUserCode(uacUser.getUserCode());
            uacCompanyUser.setDataType("0"); // 本体统用户管理添加的用户，默认都是系统用户
            uacCompanyUserService.save(uacCompanyUser);*/
        } else {
            UacUserEntity uacUserEntity = this.getById(uacUser.getId());
            Preconditions.checkArgument(uacUserEntity != null, "用户不存在");
            // 1.更新用户信息
            if(!uacUserEntity.getLoginPwd().equals(uacUser.getLoginPwd())) {
//            	uacUser.setLoginPwd(passwordEncoder.encode(uacUser.getLoginPwd()));
            }
            boolean result = this.updateById(uacUser);
            if (!result) {
                throw new UacBizException(ErrorCodeEnum.UAC10011026, uacUser.getId());
            }
            // 删除用户负责区域信息
            uacUserAreaDao.delete(new QueryWrapper<UacUserAreaEntity>().eq("user_id",uacUser.getId()));
            // 新增用户负责区域信息
            this.saveUserAreaInfo(uacUser,loginAuthDto);
            // TODO 【去掉】 2.绑定业务机构关联
            /*UacCompanyUserEntity uacCompanyUser = uacCompanyUserService.getOne(
                    new QueryWrapper<UacCompanyUserEntity>().eq("user_code",uacUser.getUserCode()));
            if (uacCompanyUser == null) {
                // 添加业务机构关联
            	uacCompanyUser = new UacCompanyUserEntity();
            	uacCompanyUser.setComCode(uacUser.getBelongComCode());
            	uacCompanyUser.setUserCode(uacUser.getUserCode());
            	uacCompanyUser.setDataType("0"); // 本体统用户管理添加的用户，默认都是系统用户
                uacCompanyUserService.save(uacCompanyUser);
            } else {
                //修改业务机构关联
            	uacCompanyUser.setUserCode(uacUser.getUserCode());
            	uacCompanyUser.setComCode(uacUser.getBelongComCode());
                uacCompanyUserService.update(uacCompanyUser,
                        new QueryWrapper<UacCompanyUserEntity>().eq("user_code",uacUser.getUserCode()));
            }*/
        }

    }

    /**
     * 保存用户负责区域信息
     * @param uacUser
     * @param loginAuthDto
     */
    private void saveUserAreaInfo(UacUserEntity uacUser, LoginAuthDto loginAuthDto) {
        String[] channel = uacUser.getChannel();
        String[] service = uacUser.getService();
        Map<String, String> addrCounty = uacUser.getAddrCounty();
        UacUserAreaEntity userArea = new UacUserAreaEntity();
        userArea.setUserId(uacUser.getId());
        userArea.setType(uacUser.getType());
        if ("01".equals(uacUser.getType())) {
            if (!PublicUtil.isEmpty(addrCounty)) {
                if(!PublicUtil.isEmpty(addrCounty.get("province"))) {
                    packageUserArea(addrCounty.get("province"),"P",userArea);
                    if(!PublicUtil.isEmpty(addrCounty.get("city"))) {
                        packageUserArea(addrCounty.get("city"),"C",userArea);
                        if(!PublicUtil.isEmpty(addrCounty.get("area"))) {
                            packageUserArea(addrCounty.get("area"),"A",userArea);
                        }
                    }
                }else {
                    // 不勾选则选择全部省份
                    List<DictOptionVo> admOptions = dictCodeService.getAdmOptions("10000000");
                    List<String> provinceCodeList = new ArrayList<>();
                    for (DictOptionVo vo : admOptions) {
                        provinceCodeList.add(vo.getValue()+"-"+vo.getLabel());
                    }
                    packageUserArea(org.apache.commons.lang.StringUtils.join(provinceCodeList.toArray(),","),"P",userArea);
                }
            }else {
                // 不勾选则选择全部省份
                List<DictOptionVo> admOptions = dictCodeService.getAdmOptions("10000000");
                List<String> provinceCodeList = new ArrayList<>();
                for (DictOptionVo vo : admOptions) {
                    provinceCodeList.add(vo.getValue()+"-"+vo.getLabel());
                }
                packageUserArea(org.apache.commons.lang.StringUtils.join(provinceCodeList.toArray(),","),"P",userArea);
            }
        }else if ("02".equals(uacUser.getType())) {
            if (!PublicUtil.isEmpty(channel)) {
                userArea.setChannelCode(org.apache.commons.lang.StringUtils.join(channel, ","));
            }
        }else if ("03".equals(uacUser.getType())) {
            if (!PublicUtil.isEmpty(service)) {
                userArea.setServiceCode(org.apache.commons.lang.StringUtils.join(service, ","));
            }
        }
        userArea.setCreater(loginAuthDto.getUserName());
        userArea.setCreateTime(new Date());
        userArea.setUpdater(loginAuthDto.getUserName());
        userArea.setUpdateTime(new Date());
        uacUserAreaDao.insert(userArea);
    }

    /**
     * 封装用户负责区域地址信息
     * @param address
     * @param type
     * @param userArea
     * @return
     */
    private UacUserAreaEntity packageUserArea (String address, String type, UacUserAreaEntity userArea) {
        String[] addr = address.split(",");
        String name="";
        String code="";
        for(int i = 0; i < addr.length; i++) {
            if(i == addr.length-1){
                code += addr[i].split("-")[0] ;
                name += addr[i].split("-")[1] ;
            }else{
                code += addr[i].split("-")[0] + "," ;
                name += addr[i].split("-")[1] + "," ;
            }
        }
        if ("P".equals(type)) {
            userArea.setProvinceCode(code);
            userArea.setProvinceName(name);
        }else if ("C".equals(type)) {
            userArea.setCityCode(code);
            userArea.setCityName(name);
        }else if ("A".equals(type)) {
            userArea.setAreaCode(code);
            userArea.setAreaName(name);
        }
        return userArea;

    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public IPage<UacLogEntity> queryUserLogListWithPage(Long userId, Integer pageNum, Integer pageSize) {
        if (PublicUtil.isEmpty(userId)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011001);
        }
        //IPage<UacLogEntity> page = uacLogService.queryUserLogListWithPage(userId,pageNum,pageSize);
        IPage<UacLogEntity> page = null;
        return null;
    }

    @Override
    public boolean modifyUserStatusById(UacUserEntity uacUser, LoginAuthDto authResDto) {
        Long loginUserId = authResDto.getUserId();
        Long userId = uacUser.getId();
        if (loginUserId.equals(userId)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011023);
        }
        UacUserEntity u = this.getById(userId);
        if (u == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10011011, userId);
        }
        // 更新用户最后修改人与修改时间
        uacUser.setVersion(u.getVersion() + 1);
        uacUser.setUpdateInfo(authResDto);
        return this.updateById(uacUser);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public UserBindRoleVo getUserBindRoleDto(Long userId) {
        UserBindRoleVo userBindRoleVo = new UserBindRoleVo();
        Set<Long> alreadyBindRoleIdSet = Sets.newHashSet();
        UacUserEntity uacUser = this.getById(userId);
        if (uacUser == null) {
            log.error("找不到userId={}, 的用户", userId);
            throw new UacBizException(ErrorCodeEnum.UAC10011003, userId);
        }

        // 查询所有角色包括该用户拥有的角色
        List<BindRoleDto> bindRoleDtoList = uacUserDao.selectAllNeedBindRole(GlobalConstant.Sys.SUPER_MANAGER_ROLE_ID);
        // 该角色已经绑定的用户
//        List<UacRoleUserEntity> setAlreadyBindRoleSet = uacRoleUserService.listByUserId(userId);
//
//        Set<BindRoleDto> allUserSet = new HashSet<>(bindRoleDtoList);
//
//        for (UacRoleUserEntity uacRoleUser : setAlreadyBindRoleSet) {
//            alreadyBindRoleIdSet.add(uacRoleUser.getRoleId());
//        }

//        userBindRoleVo.setAllRoleSet(allUserSet);
        userBindRoleVo.setAlreadyBindRoleIdSet(alreadyBindRoleIdSet);

        return userBindRoleVo;
    }

    @Override
    public void bindUserRoles(BindUserRolesDto bindUserRolesDto, LoginAuthDto authResDto) {

        if (bindUserRolesDto == null) {
            log.error("参数不能为空");
            throw new IllegalArgumentException("参数不能为空");
        }

        Long operUserId = bindUserRolesDto.getUserId();
        Long loginUserId = authResDto.getUserId();
        List<Long> roleIdList = bindUserRolesDto.getRoleIdList();

        if (null == operUserId) {
            throw new UacBizException(ErrorCodeEnum.UAC10011001);
        }

        // 任何用户不能操作admin用户
        if (Objects.equals(operUserId, GlobalConstant.Sys.SUPER_MANAGER_USER_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011034);
        }

        UacUserEntity user = this.queryByUserId(operUserId);

        if (user == null) {
            log.error("找不到用户信息 operUserId={}", operUserId);
            throw new UacBizException(ErrorCodeEnum.UAC10011003, operUserId);
        }

        if (PublicUtil.isNotEmpty(roleIdList) && roleIdList.contains(GlobalConstant.Sys.SUPER_MANAGER_ROLE_ID)) {
            log.error("操作超级管理员角色 userId={}", loginUserId);
            throw new UacBizException(ErrorCodeEnum.UAC10011023);
        }

        // 1. 先取消对该角色的用户绑定(不包含超级管理员用户)
//        List<UacRoleUserEntity> userRoles = uacRoleUserService.listByUserId(operUserId);
//
//        if (PublicUtil.isNotEmpty(userRoles)) {
//            uacRoleUserService.deleteByUserId(operUserId);
//        }

        // 更新用户的操作时间
        final UacUserEntity updateUser = new UacUserEntity();
        updateUser.setId(operUserId);
        updateUser.setUpdateInfo(authResDto);
        this.updateById(updateUser);

        if (PublicUtil.isEmpty(roleIdList)) {
            // 取消该角色的所有用户的绑定
            log.info("绑定角色成功");
            return;
        }

        // 绑定所选用户
//        for (Long roleId : roleIdList) {
//            UacRoleEntity uacRole = uacRoleService.getById(roleId);
//            if (uacRole == null) {
//                log.error("找不到绑定的角色. roleId={}", roleId);
//                throw new UacBizException(ErrorCodeEnum.UAC10012008, roleId);
//            }
//            uacRoleUserService.saveRoleUser(operUserId, roleId);
//        }
    }





    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public UacUserEntity findByLoginName(String loginName) {
        log.info("findByLoginName - 根据用户名查询【启用】用户信息. loginName={}", loginName);
        UacUserEntity uacUserEntity = this.getOne(new QueryWrapper<UacUserEntity>().eq("login_name",loginName).eq("status","ENABLE"));
        return uacUserEntity;
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public UacUserEntity findUserInfoByUserId(Long userId) {
        return uacUserDao.selectUserInfoByUserId(userId);
    }

//    @Override
//    public Collection<GrantedAuthority> loadUserAuthorities(Long userId) {
//        List<UacActionEntity> ownAuthList = uacActionService.getOwnActionListByUserId(userId);
//        List<GrantedAuthority> authList = Lists.newArrayList();
//        for (UacActionEntity action : ownAuthList) {
//            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(action.getUrl());
//            authList.add(grantedAuthority);
//        }
//        return authList;
//    }

    @Override
    public void handlerLoginData(String token,Map<String,String> userInfoMap,HttpServletRequest request) {

        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获取客户端操作系统
        final String os = userAgent.getOperatingSystem().getName();
        //获取客户端浏览器
        final String browser = userAgent.getBrowser().getName();
        final String remoteAddr = RequestUtil.getRemoteAddr(request);
        final String remoteLocation = "";
        final String requestURI = request.getRequestURI();

        UacUserEntity uacUserEntity = new UacUserEntity();
        Long userId = Long.valueOf(userInfoMap.get("userId"));
        uacUserEntity.setLastLoginIp(remoteAddr);
        uacUserEntity.setId(userId);
        uacUserEntity.setLastLoginTime(new Date());
        uacUserEntity.setLastLoginLocation(remoteLocation);

        Long groupId = userInfoMap.get("groupId")!=null?Long.valueOf(userInfoMap.get("groupId")):null;
        String groupName = userInfoMap.get("groupName");

        LoginAuthDto loginAuthDto = new LoginAuthDto(userId,userInfoMap.get("userCode"),userInfoMap.get("loginName"),
                userInfoMap.get("userName"),groupId,groupName,
                userInfoMap.get("belongComCode"),userInfoMap.get("belongComName"));
        loginAuthDto.setComCode(userInfoMap.get("belongComCode"));
        loginAuthDto.setComName(userInfoMap.get("belongComName"));
        // 记录token日志
        uacUserTokenService.saveUserToken(token, null, loginAuthDto, request);
        // 记录最后登录信息
        taskExecutor.execute(() -> this.updateUser(uacUserEntity));
        // 记录操作日志

        UacLogEntity uacLogEntity = new UacLogEntity();
        uacLogEntity.setGroupId(groupId);
        uacLogEntity.setGroupName(groupName);
        uacLogEntity.setIp(remoteAddr);
        uacLogEntity.setLocation(remoteLocation);
        uacLogEntity.setOs(os);
        uacLogEntity.setBrowser(browser);
        uacLogEntity.setRequestUrl(requestURI);
        uacLogEntity.setLogType(LogTypeEnum.LOGIN_LOG.getType());
        uacLogEntity.setLogName(LogTypeEnum.LOGIN_LOG.getName());

        taskExecutor.execute(() -> uacLogService.saveLog(uacLogEntity, loginAuthDto));
    }

    @Override
    public boolean updateUser(UacUserEntity uacUser) {
        log.info("更新用户信息 uacUser={}", uacUser);
        boolean updateResult = this.updateById(uacUser);
        if (!updateResult) {
            log.info("用户【 {} 】修改用户信息失败", uacUser.getId());
        } else {
            log.info("用户【 {} 】修改用户信息成功", uacUser.getId());
        }
        return updateResult;
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public UacUserEntity queryByUserId(Long userId) {
        log.info("queryByUserId - 根据用户查询用户信息接口. userId={}", userId);
        UacUserEntity uacUser = this.getById(userId);
//        if (PublicUtil.isNotEmpty(uacUser)) {
//            uacUser.setLoginPwd("");
//        }
        return uacUser;
    }

    @Override
    public void resetLoginPwd(Long userId, LoginAuthDto loginAuthDto) {
        if (userId == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10011001);
        }
        UacUserEntity uacUser = this.queryByUserId(userId);
        if (uacUser == null) {
            log.error("找不到用户. userId={}", userId);
            throw new UacBizException(ErrorCodeEnum.UAC10011003, userId);
        }

//        Preconditions.checkArgument(!StringUtils.isEmpty(uacUser.getEmail()), "邮箱地址不能为空");

//        String newLoginPwd = RandomUtil.createComplexCode(8);
//        System.out.println(newLoginPwd);
        String newLoginPwd = "000000";
        //uacUser.setLoginPwd(passwordEncoder.encode(newLoginPwd));
        uacUser.setLoginPwd(newLoginPwd);
        short isChangedPwd = 0;
        uacUser.setIsChangedPwd(isChangedPwd);
        uacUser.setUpdateInfo(loginAuthDto);
        boolean updateResult = this.updateUser(uacUser);
        if (!updateResult) {
            log.error("用户【 {} 】重置密码失败", uacUser.getLoginName());
        } else {
            log.info("用户【 {} 】重置密码失败", uacUser.getLoginName());
        }
    }



    @Override
    public void batchResetLoginPwd(List<Long> userIds, LoginAuthDto loginAuthDto) {
        if (userIds == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10011001);
        }
        for (Long userId : userIds) {
            UacUserEntity uacUser = this.queryByUserId(userId);
            if (uacUser == null) {
                log.error("找不到用户. userId={}", userId);
                throw new UacBizException(ErrorCodeEnum.UAC10011003, userId);
            }
            // 重置密码
            String newLoginPwd = "zx123456789";
            uacUser.setLoginPwd(newLoginPwd);
            short isChangedPwd = 0;
            uacUser.setIsChangedPwd(isChangedPwd);
            uacUser.setUpdateInfo(loginAuthDto);
            boolean updateResult = this.updateUser(uacUser);
            if (!updateResult) {
                log.error("用户【 {} 】重置密码失败", uacUser.getLoginName());
            } else {
                log.info("用户【 {} 】重置密码失败", uacUser.getLoginName());
            }
        }
    }

    @Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<UserMenuDto> queryUserMenuDtoData(LoginAuthDto authResDto) {
//		// 返回的结果集
//		List<UserMenuDto> list = Lists.newArrayList();
//		List<MenuVo> menuList; // 该用户下所有的菜单集合
//		Long userId = authResDto.getUserId();
//		List<Long> ownerMenuIdList = Lists.newArrayList();
//		Preconditions.checkArgument(!PubUtils.isNull(authResDto, userId), "无访问权限");
//
//		// 查询该用户下所有的菜单Id集合
//		UacUserMenu query = new UacUserMenu();
//		query.setUserId(userId);
//		List<UacUserMenu> userMenus = uacUserMenuMapper.select(query);
//		for (UacUserMenu userMenu : userMenus) {
//			if (PublicUtil.isEmpty(userMenu.getUserId())) {
//				continue;
//			}
//			ownerMenuIdList.add(userMenu.getMenuId());
//		}
//
//
//		//判断是否为admin用户 如果是则返回所有菜单, 如果不是走下面流程
//		menuList = uacMenuService.getMenuVoList(userId, 1L);
//		for (MenuVo menuVo : menuList) {
//			// 一级菜单
//			UserMenuDto userMenuDto = new UserMenuDto();
//			userMenuDto.setFistMenuIcon(menuVo.getIcon());
//			userMenuDto.setFistMenuName(menuVo.getMenuName());
//			List<MenuVo> sub2Menu = menuVo.getSubMenu();
//			List<UserMenuChildrenDto> children = Lists.newArrayList();
//			for (MenuVo vo2 : sub2Menu) {
//				// 二级菜单 如果没有子节直接放入
//				if (!vo2.isHasMenu()) {
//					UserMenuChildrenDto userMenuChildrenDto = new UserMenuChildrenDto(vo2);
//					//判断是否含有该菜单, 含有为true, 不含有为false
//					if (ownerMenuIdList.contains(vo2.getId())) {
//						userMenuChildrenDto.setChecked(true);
//					}
//					children.add(userMenuChildrenDto);
//					continue;
//				}
//				// 如果二级节点有子节继续循环三级菜单
//				List<MenuVo> sub3Menu = vo2.getSubMenu();
//				for (MenuVo vo3 : sub3Menu) {
//					UserMenuChildrenDto dto = new UserMenuChildrenDto(vo3);
//					//判断是否含有该菜单, 含有为true, 不含有为false
//					if (ownerMenuIdList.contains(vo3.getId())) {
//						dto.setChecked(true);
//					}
//					children.add(dto);
//				}
//			}
//			userMenuDto.setChildren(children);
//			list.add(userMenuDto);
//		}

//		return list;
    	return null;
	}

    @Override
    public UserInfoVo queryUserInfoById(Long userId) {
        UserInfoVo vo = new UserInfoVo();
        UacUserEntity userData =this.getOne(new QueryWrapper<UacUserEntity>().eq("id",userId));
        try{
            BeanUtils.copyProperties(vo,userData);
        }catch (Exception e){
            e.printStackTrace();
        }
        String userComcode = this.uacCompanyUserService.getOne(new QueryWrapper<UacCompanyUserEntity>().eq("user_code",userData.getUserCode())).getComCode();
        vo.setBelongComName(this.uacCompanyService.getOne(new QueryWrapper<UacCompanyEntity>().eq("com_code",userComcode)).getComShortName());
        List<UacRoleUserEntity> uacRoleUserList =  this.uacRoleUserService.list(new QueryWrapper<UacRoleUserEntity>().eq("user_id",userId));
        Map roleMap = new ConcurrentHashMap();
        for(UacRoleUserEntity data:uacRoleUserList){
            UacRoleEntity uacRoleEntity = this.uacRoleService.getOne(new QueryWrapper<UacRoleEntity>().eq("id",data.getRoleId()));
            roleMap.put(uacRoleEntity.getId(),uacRoleEntity.getRoleName());
        }
        vo.setRolesMap(roleMap);
        return vo;
    }

    /**
     * 查询用户下拉列表
     * @param userType：用户类别
     * @param upperVal：归属的上级，级联显示时会用到
     * @param belongFlag：是否考虑用户的归属机构
     * @param loginAuthDto：登录信息
     * @return
     */
    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<DictOptionVo> getSelectOptions(String userType, String upperVal, String belongFlag, LoginAuthDto loginAuthDto){
    	List<DictOptionVo> options = null;
    	// 考虑用户归属机构的情况下，用户列表只显示同一机构或下级机构的用户
    	String[] belongCodes = null; // 目标用户的归属机构
    	if("true".equals(belongFlag)) {
    		if(!"".equals(loginAuthDto.getBelongComCode())) {
//    			belongCodes = "'" + loginAuthDto.getBelongComCode() + "'";
        		List<CompanyTreeVo> belongList = uacCompanyService.getComAndsubComCodeVo(loginAuthDto.getBelongComCode());
        		belongCodes = new String[belongList.size() + 1];
        		belongCodes[0] = loginAuthDto.getBelongComCode();
        		int i = 1;
        		for(CompanyTreeVo company : belongList) {
//        			belongCodes += ",'" + company.getMenuCode() + "'";
        			belongCodes[i++] = company.getMenuCode();
        		}
    		}
    	}
    	String[] upperVals = null;
    	if(!PublicUtil.isEmpty(upperVal)) {
    		upperVals = upperVal.split(",");
    	}
    	if("ZX".equals(userType)) {
    		options = this.uacUserDao.getZXOptions(upperVals, belongCodes);
    	} else if ("ZXGW".equals(userType)) {
    		options = this.uacUserDao.getZXOptions(upperVals, belongCodes);
    	}
    	return options;
    }


}
